<template>
  <div style="height: 6vh; background-image: linear-gradient(to right, #fffacd, #add8e6); padding: 10px 20px;">
    <span style="line-height: 60px; font-size: 20px;font-weight: bold">公告信息</span>
    <el-button type="primary" style="float: right; margin-top: 13px;" @click="beforeAddAnnouncement">新增公告
    </el-button>
  </div>
  <!-- 新增公告弹窗 -->
  <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      style="width: 50%;padding:40px;"
      :before-close="handleClose">
    <el-form label-width="80px">
      <el-form-item label="公告名称">
        <el-input v-model="saveAnnouncementForm.title" placeholder="请输入公告名称"></el-input>
      </el-form-item>
      <el-form-item label="公告类型">
        <el-select v-model="saveAnnouncementForm.type" placeholder="请选择公告类型">
          <el-option label="系统通知" value="系统通知"/>
          <el-option label="活动公告" value="活动公告"/>
          <el-option label="紧急通知" value="紧急通知"/>
        </el-select>
      </el-form-item>
      <el-form-item label="公告内容">
        <el-input v-model="saveAnnouncementForm.content" type="textarea" :rows="5" placeholder="请输入公告内容"></el-input>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
            v-model="saveAnnouncementForm.publishTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发布时间"
            :disabled-date="disableFutureDate"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="公告状态">
        <el-radio-group v-model="saveAnnouncementForm.status">
          <el-radio border label="草稿" value="0"></el-radio>
          <el-radio border label="已发布" value="1"></el-radio>
          <el-radio border label="已过期" value="2" :disabled="isExpiredDisabled"></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveAnnouncement">保存</el-button>
    </template>
  </el-dialog>
  <!-- 公告搜索卡片 -->
  <el-card style="margin: 20px; height: 70px;">
    <el-form :inline="true">
      <el-form-item label="公告名称" style="width: 290px;">
        <el-input v-model="searchForm.title" placeholder="请输入公告名称"
                  style="width: 220px;"
                  @keydown.enter="loadAnnouncements"></el-input>
      </el-form-item>
      <el-form-item label="公告类型" style="width: 290px;">
        <el-select v-model="searchForm.type"
                   placeholder="请选择公告类型" @change="loadAnnouncements">
          <el-option label="系统通知" value="系统通知"/>
          <el-option label="活动公告" value="活动公告"/>
          <el-option label="紧急通知" value="紧急通知"/>
        </el-select>
      </el-form-item>
      <el-form-item label="公告状态" style="width: 290px;">
        <el-select v-model="searchForm.status"
                   placeholder="请选择公告状态" @change="loadAnnouncements">
          <el-option label="草稿" value="0"/>
          <el-option label="已发布" value="1"/>
          <el-option label="已过期" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadAnnouncements">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 公告数据表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="announcementList">
      <el-table-column label="编号" type="index" align="center" width="100"></el-table-column>
      <el-table-column label="公告名称" prop="title" align="center"></el-table-column>
      <el-table-column label="公告类型" prop="type" align="center"></el-table-column>
      <el-table-column label="发布时间" prop="publishTime" align="center"></el-table-column>
      <el-table-column label="公告状态" prop="status" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : scope.row.status === '0' ? 'warning' : 'danger'">
            {{ scope.row.status === '1' ? '已发布' : scope.row.status === '0' ? '草稿' : '已过期' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link :disabled="scope.row.level==40"
                     @click="editAnnouncement(scope.row.id)">编辑
          </el-button>
          <el-button type="primary" link :disabled="scope.row.level==40"
                     @click="deleteAnnouncement(scope.row.id)">删除
          </el-button>
          <el-button type="primary" link :disabled="scope.row.level==40"
                     @click="viewAnnouncement(scope.row.id)">查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

  </el-card>
  <!-- 查看公告详情弹窗 -->
  <el-dialog v-model="detailDialogVisible" title="公告详情" width="50%"
             :before-close="handleClose">
    <el-form :model="currentAnnouncement" label-width="100px">
      <el-form-item label="公告名称">
        <span>{{ currentAnnouncement.title }}</span>
      </el-form-item>
      <el-form-item label="公告类型">
        <span>{{ currentAnnouncement.type }}</span>
      </el-form-item>
      <el-form-item label="公告内容">
        <span>{{ currentAnnouncement.content }}</span>
      </el-form-item>
      <el-form-item label="发布时间">
        <span>{{ currentAnnouncement.publishTime }}</span>
      </el-form-item>
      <el-form-item label="公告状态">
        <el-tag
            :type="currentAnnouncement.status === '1' ? 'success' : currentAnnouncement.status === '0' ? 'warning' : 'danger'">
          {{ currentAnnouncement.status === '1' ? '已发布' : currentAnnouncement.status === '0' ? '草稿' : '已过期' }}
        </el-tag>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {computed, onMounted, ref, watch} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

// 公告列表数据
const announcementList = ref([]);

// 搜索表单
const searchForm = ref({
  title: '',
  status: '',
  type: ''
});

// 加载公告列表
const loadAnnouncements = () => {
  let data = qs.stringify(searchForm.value);
  axios.get(BASE_URL + '/p1/announce/select?' + data)
      .then((response) => {
        if (response.data.code == 2000) {
          announcementList.value = response.data.data;
          console.log(announcementList.value)
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};

// 页面加载时获取公告列表
onMounted(() => {
  loadAnnouncements();
});

// 重置搜索条件
const resetSearch = () => {
  searchForm.value = {title: '', status: '',type: ''};
  loadAnnouncements();
};

// 新增公告表单
const saveAnnouncementForm = ref({
  id: '',
  title: '',
  type: '',
  content: '',
  publishTime: '',
  status: ''
});

// 当前查看的公告详情
const currentAnnouncement = ref({});

// 弹窗控制
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const dialogTitle = ref('新增公告');

// 打开新增公告弹窗
const beforeAddAnnouncement = () => {
  dialogTitle.value = '新增公告';
  dialogVisible.value = true;
};

// 处理弹窗关闭
const handleClose = () => {
  if (confirm('您是否要关闭本弹窗?')) {
    saveAnnouncementForm.value = {};
    dialogVisible.value = false;
    detailDialogVisible.value = false
  }
};

// 保存公告
const saveAnnouncement = () => {
  if (!saveAnnouncementForm.value.title || saveAnnouncementForm.value.title.trim() == '') {
    ElMessage.error('请输入公告名称！');
    return;
  }
  if (!saveAnnouncementForm.value.type || saveAnnouncementForm.value.type.trim() == '') {
    ElMessage.error('请选择公告类型！');
    return;
  }
  if (!saveAnnouncementForm.value.content || saveAnnouncementForm.value.content.trim() == '') {
    ElMessage.error('请输入公告内容！');
    return;
  }
  if (!saveAnnouncementForm.value.publishTime) {
    ElMessage.error('请选择公告发布时间！');
    return;
  }
  // 校验发布时间是否超过当前时间
  const publishTime = new Date(saveAnnouncementForm.value.publishTime);
  const currentTime = new Date();
  if (publishTime > currentTime) {
    ElMessage.error('发布时间不能超过当前时间！');
    return;
  }
  let data = qs.stringify(saveAnnouncementForm.value);
  axios.post(BASE_URL + '/p1/announce/save', data)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('公告保存成功！');
          dialogVisible.value = false;
          saveAnnouncementForm.value = {};
          loadAnnouncements();
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};

// 编辑公告
const editAnnouncement = (id) => {
  dialogTitle.value = '编辑公告';
  dialogVisible.value = true;
  axios.get(BASE_URL + '/p1/announce/select?id=' + id)
      .then((response) => {
        if (response.data.code == 2000) {
          saveAnnouncementForm.value = response.data.data[0];
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};

// 删除公告
const deleteAnnouncement = (id) => {
  if (confirm('确定要删除此公告吗？')) {
    axios.delete(BASE_URL + '/p1/announce/delete/' + id)
        .then((response) => {
          if (response.data.code == 2000) {
            ElMessage.success('删除公告成功');
            loadAnnouncements();
          } else {
            ElMessage.error(response.data.msg);
          }
        });
  }
};

// 查看公告详情
const viewAnnouncement = (id) => {
  axios.get(BASE_URL + '/p1/announce/select?id=' + id)
      .then((response) => {
        if (response.data.code == 2000) {
          currentAnnouncement.value = response.data.data[0];
          detailDialogVisible.value = true;
        } else {
          ElMessage.error(response.data.msg);
        }
      });
};

// 禁用未来日期
const disableFutureDate = (date) => {
  const currentDate = new Date();
  return date > currentDate;
}

// 计算属性：是否禁用“已过期”状态
const isExpiredDisabled = computed(() => {
  //新增时禁用“已过期”
  if (dialogTitle.value === '新增公告') {
    return true;
  }
  //编辑时，根据公告类型动态禁用
  return saveAnnouncementForm.value.type !== '活动公告';
})

</script>

<style scoped>
</style>